package com.itbaizhan.common;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class jdbcUtils {

        private static String url;
        private static  String name;
        private static String pwd;

        static{
            Properties prop =new Properties();
            InputStream is=jdbcUtils.class.getClassLoader().getResourceAsStream("ls.properties");
            try {
                prop.load(is);
                url=prop.getProperty("url");
                name=prop.getProperty("username");
                pwd=prop.getProperty("pwd");
                String divername=prop.getProperty("driver");
                Class.forName(divername);


            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }


        }

        public static Connection getConnection(){
            Connection connection=null;
            try {
                connection = DriverManager.getConnection(url,name,pwd);


            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
return connection;

        }
    public static void closeStatement(Statement statement){
        try {
            statement.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
public static void closeConnection(Connection connection){
    try {
        connection.close();
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }

}

public static void commit(Connection connnection){
    try {
        connnection.commit();
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}
public static void rollback(Connection connection){
    try {
        connection.rollback();
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }

}
public static void closeResource(Statement statement,Connection connection){
            closeStatement(statement);
            closeConnection(connection);

}
    public static void closeResultSet(ResultSet resultSet) {
        try {
            resultSet.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
    public static void closeResource(ResultSet resultSet,Statement statement,Connection connection){
        //先关闭ResultSet
        closeResultSet(resultSet);
        //在闭Statement对象
        closeStatement(statement);
        //最后关闭Connection对象
        closeConnection(connection);
    }
}


